package com.yq.activemq.topic;


import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Pub {

    /**
     * 消息服务器地址
     */
    public static final String BROKER_URL = "tcp://localhost:61616";

    public static void main(String[] args) {
        Pub pub = new Pub();
        for (int i = 0; i < 10; i++) {
            pub.sendMessage("Hello ActiveMQ Topic " + i);
        }
    }

    private void sendMessage(String msg) {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        try {
            connection = connectionFactory.createConnection();
            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            TextMessage message = session.createTextMessage(msg);
            // 和p2p方式不同，p2p创建的是Queue；Pub/Sub创建的是topic
            Topic topic = session.createTopic("myTopic");
            producer = session.createProducer(topic);
            // 开启持久化
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            producer.send(message);
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (producer != null) {
                    producer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

